const Service = require('egg').Service;
class ActService extends Service {
    // 界面列表
    async list({ pageIndex = 0, pageSize = 10 }) {
        var pageIndex = pageIndex * 1 * pageSize;
        var pageSize = pageSize * 1;
        const options = {
            offset: pageIndex,
            limit: pageSize,
            attributes: ['id', 'title', 'desc', 'type', 'member', 'vote'],
            order: [['created_at', 'ASC']]
        };
        const act = this.ctx.model.Act.findAndCountAll(options);
        return act;
    }

    // 界面详情
    async find(id) {
        const act = await this.ctx.model.Act.findById(id);
        if (!act) {
            this.ctx.throw(500, "节目不存在");
        }
        return act;
    }

    // 添加节目
    async create(data) {
        const options = {
            where: {
                title: data.title
            }
        };
        const act = await this.ctx.model.Act.findOne(options);
        if (act) {
            this.ctx.throw(500, "界面名称已存在");
        }
        return this.ctx.model.Act.create(data);
    }

    // 编辑节目
    async update(data) {
        const act = await this.ctx.model.Act.findById(data.id);
        if (!act) {
            this.ctx.throw(500, "更新失败");
        }
        return act.updateAttributes(data);
    }

    // 删除节目
    async del(id) {
        console.log('--------：' + id);
        const act = await this.ctx.model.Act.findById(id);

        if (!act) {
            this.ctx.throw(500, "删除失败");
        }
        return act.destroy();
    }

    // 界面投票
    async vote(post) {
        var User = this.ctx.model.User;
        var Vote = this.ctx.model.Vote;
        var Act = this.ctx.model.Act;
        var self = this;
        const uid = post.uid;
        const aid = post.aid;
        const t = await this.ctx.model.transaction();
        const user = await User.findOne({
            where: { id: uid },
            transaction: t
        });

        if (!user.vote) {
            const user = await User.update({ vote: true }, {
                where: { id: uid },
                transaction: t
            });

            for (var item of aid) {

                // 自增投票记录
                await Act.increment({
                    vote: 1
                },
                    {
                        where: {
                            id: item
                        },
                        transaction: t
                    });

                // 创建一条投票记录
                await Vote.create(
                    {
                        uid: uid,
                        aid: item
                    },
                    {
                        transaction: t
                    });
            }




            await t.commit();

        } else {
            t.rollback()
            this.ctx.throw(500, "亲，你已经投过票了哦~");
        }
    }
}
module.exports = ActService;